package com.xyy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xyy.common.PageResult;
import com.xyy.dto.HealthStatisticsDTO;
import com.xyy.entity.Patient;
import com.xyy.mapper.PatientMapper;
import com.xyy.service.PatientService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 就诊人Service实现类
 */
@Slf4j
@Service
public class PatientServiceImpl implements PatientService {
    
    @Resource
    private PatientMapper patientMapper;
    
    @Override
    public Patient addPatient(Patient createDTO, Long userId) {
        // 检查身份证号是否已存在
        QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id_card", createDTO.getIdCard());
        Patient existingPatient = patientMapper.selectOne(queryWrapper);
        if (existingPatient == null) {
            // 创建新的就诊人
            Patient patient = new Patient();
            BeanUtils.copyProperties(createDTO, patient);
            patient.setUserId(userId);
            patient.setCreatedAt(LocalDateTime.now());
            patient.setUpdatedAt(LocalDateTime.now());
            
            // 设置健康指标默认值
            patient.setHeight("未测量");
            patient.setWeight("未测量");
            patient.setBloodOxygen("未测量");
            patient.setVision("未测量");
            patient.setBloodPressure("未测量");
            patient.setBloodSugar("未测量");
            patient.setBloodLipid("未测量");
            patient.setDevelopment("未测量");
            patient.setOtherConditions("未测量");
            
            patientMapper.insert(patient);
            return patient;
        } else {
            throw new RuntimeException("该身份证号已存在");
        }
    }
    
    @Override
    public boolean deletePatient(Long patientId, Long userId) {
        // 检查就诊人是否存在且属于当前用户
        Patient patient = getPatientById(patientId, userId);
        if (patient == null) {
            return false;
        }
        
        return patientMapper.deleteById(patientId) > 0;
    }
    
    @Override
    public Patient updatePatient(Patient patient, Long userId) {
        // 检查就诊人是否存在且属于当前用户
        Patient existingPatient = getPatientById(patient.getId(), userId);
        if (existingPatient == null) {
            throw new RuntimeException("就诊人不存在或无权限修改");
        }
        
        // 如果修改了身份证号，检查是否与其他就诊人重复
        if (patient.getIdCard() != null && !patient.getIdCard().equals(existingPatient.getIdCard())) {
            QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id_card", patient.getIdCard());
            queryWrapper.ne("id", patient.getId());
            Patient duplicatePatient = patientMapper.selectOne(queryWrapper);
            if (duplicatePatient != null) {
                throw new RuntimeException("该身份证号已存在");
            }
        }
        
        // 设置更新时间
        patient.setUpdatedAt(LocalDateTime.now());
        
        patientMapper.updateById(patient);
        return getPatientById(patient.getId(), userId);
    }
    
    @Override
    public List<Patient> getPatientList(Long userId) {
        QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        queryWrapper.orderByDesc("created_at");
        
        return patientMapper.selectList(queryWrapper);
    }
    
    @Override
    public Patient getPatientById(Long patientId, Long userId) {
        QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", patientId);
        queryWrapper.eq("user_id", userId);
        
        return patientMapper.selectOne(queryWrapper);
    }
    
    // ==================== 管理员方法实现 ====================
    
    @Override
    public Patient adminUpdateHealth(Patient patient) {
        // 检查就诊人是否存在
        Patient existingPatient = patientMapper.selectById(patient.getId());
        if (existingPatient == null) {
            throw new RuntimeException("就诊人不存在");
        }
        
        // 只更新健康指标相关字段
        Patient updatePatient = new Patient();
        updatePatient.setId(patient.getId());
        updatePatient.setHeight(patient.getHeight());
        updatePatient.setWeight(patient.getWeight());
        updatePatient.setBloodOxygen(patient.getBloodOxygen());
        updatePatient.setVision(patient.getVision());
        updatePatient.setBloodPressure(patient.getBloodPressure());
        updatePatient.setBloodSugar(patient.getBloodSugar());
        updatePatient.setBloodLipid(patient.getBloodLipid());
        updatePatient.setDevelopment(patient.getDevelopment());
        updatePatient.setOtherConditions(patient.getOtherConditions());
        updatePatient.setUpdatedAt(LocalDateTime.now());
        
        patientMapper.updateById(updatePatient);
        return patientMapper.selectById(patient.getId());
    }
    
    @Override
    public List<Patient> adminGetAllPatients() {
        QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("created_at");
        
        return patientMapper.selectList(queryWrapper);
    }
    
    @Override
    public Patient adminGetPatientById(Long id) {
        return patientMapper.selectById(id);
    }
    
    @Override
    public Integer countHealthRecordsByDoctor(Long doctorId) {
        return patientMapper.countHealthRecordsByDoctor(doctorId);
    }
    
    // ==================== 健康数据统计方法实现 ====================
    
    @Override
    public HealthStatisticsDTO getHealthStatistics() {
        HealthStatisticsDTO statistics = new HealthStatisticsDTO();
        
        try {
            // 获取各种分布统计
            statistics.setGenderDistribution(patientMapper.getGenderDistribution());
            statistics.setAgeDistribution(patientMapper.getAgeDistribution());
            statistics.setHeightDistribution(patientMapper.getHeightDistribution());
            statistics.setWeightDistribution(patientMapper.getWeightDistribution());
            statistics.setBloodPressureDistribution(patientMapper.getBloodPressureDistribution());
            statistics.setBloodSugarDistribution(patientMapper.getBloodSugarDistribution());
            statistics.setBloodOxygenDistribution(patientMapper.getBloodOxygenDistribution());
            statistics.setVisionDistribution(patientMapper.getVisionDistribution());
            statistics.setAllergyStatistics(patientMapper.getAllergyStatistics());
            statistics.setMedicalHistoryStatistics(patientMapper.getMedicalHistoryStatistics());
            
            // 获取总数统计
            statistics.setTotalPatients(patientMapper.getTotalPatients());
            statistics.setMeasuredPatients(patientMapper.getMeasuredPatients());
            
            // 获取数据完整性统计
            List<Map<String, Object>> completenessList = patientMapper.getDataCompleteness();
            Map<String, Long> completenessMap = new HashMap<>();
            for (Map<String, Object> item : completenessList) {
                String name = (String) item.get("name");
                Long value = ((Number) item.get("value")).longValue();
                completenessMap.put(name, value);
            }
            statistics.setDataCompleteness(completenessMap);
            
            log.info("健康数据统计获取成功，总就诊人数: {}", statistics.getTotalPatients());
            
        } catch (Exception e) {
            log.error("获取健康数据统计失败", e);
            throw new RuntimeException("获取健康数据统计失败: " + e.getMessage());
        }
        
        return statistics;
    }
    
    @Override
    public PageResult<Patient> getPatientHealthDataPage(Integer current, Integer size, String startDate, String endDate) {
        try {
            // 创建分页对象
            Page<Patient> page = new Page<>(current, size);
            
            // 构建查询条件
            QueryWrapper<Patient> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByDesc("updated_at");
            
            // 添加日期范围条件
            if (startDate != null && !startDate.trim().isEmpty()) {
                try {
                    LocalDateTime start = LocalDateTime.parse(startDate + " 00:00:00", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    queryWrapper.ge("updated_at", start);
                } catch (Exception e) {
                    log.warn("开始日期格式错误: {}", startDate);
                }
            }
            
            if (endDate != null && !endDate.trim().isEmpty()) {
                try {
                    LocalDateTime end = LocalDateTime.parse(endDate + " 23:59:59", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    queryWrapper.le("updated_at", end);
                } catch (Exception e) {
                    log.warn("结束日期格式错误: {}", endDate);
                }
            }
            
            // 执行分页查询
            Page<Patient> result = patientMapper.selectPage(page, queryWrapper);
            
            // 构建分页结果
            PageResult<Patient> pageResult = new PageResult<>();
            pageResult.setRecords(result.getRecords());
            pageResult.setTotal(result.getTotal());
            pageResult.setCurrent(result.getCurrent());
            pageResult.setSize(result.getSize());
            pageResult.setPages(result.getPages());
            
            log.info("分页查询患者健康数据成功，当前页: {}, 每页大小: {}, 总记录数: {}", current, size, result.getTotal());
            
            return pageResult;
            
        } catch (Exception e) {
            log.error("分页查询患者健康数据失败", e);
            throw new RuntimeException("分页查询患者健康数据失败: " + e.getMessage());
        }
    }
} 